﻿//Copyright 2010 http://tv4home.codeplex.com
//This file is part of TV4Home.Client.TVViewer.
//TV4Home.Client.TVViewer is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
//TV4Home.Client.TVViewer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//You should have received a copy of the GNU Lesser General Public License along with TV4Home.Client.TVViewer. If not, see http://www.gnu.org/licenses/.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;
using System.ServiceModel;
using System.Windows.Interop;
using System.Runtime.InteropServices;

namespace TV4Home.Client.Desktop.TVViewer
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {


        ITVEInteraction tvWebClient = null;
        TVViewer.Pages.TVViewer tvViewerPage;
        TVViewer.Pages.Schedules tvSchedulesPage = new TVViewer.Pages.Schedules();
        private const int WM_SYSCOMMAND = 0x112;
        private readonly static TimeSpan DOUBLE_CLICK_SPAN = TimeSpan.FromMilliseconds(500);
        private HwndSource _hwndSource;
        private DateTime _headerLastClick = DateTime.MinValue;

        #region Overrides

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            _hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            IntPtr handle = _hwndSource.Handle; //(new WindowInteropHelper(this)).Handle;            
            //HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WindowProc));
        }

        #endregion

        #region Handlers

        private void Header_Drag(object sender, MouseButtonEventArgs e)
        {
            if (DateTime.Now.Subtract(_headerLastClick) <= DOUBLE_CLICK_SPAN)
            {
                this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
            }
            _headerLastClick = DateTime.Now;

            if (Mouse.LeftButton == MouseButtonState.Pressed) this.DragMove();
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void RestoreButton_Click(object sender, RoutedEventArgs e)
        {
            
            this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        #endregion

        #region Window Resize Related

        // based on http://blog.kirupa.com/?p=256

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        private void ResizeWindow(ResizeDirection direction)
        {
            SendMessage(_hwndSource.Handle, WM_SYSCOMMAND, (IntPtr)(61440 + direction), IntPtr.Zero);
        }

        private void ResetCursor(object sender, MouseEventArgs e)
        {
            if (Mouse.LeftButton != MouseButtonState.Pressed)
            {
                this.Cursor = Cursors.Arrow;
            }
        }

        private void Resize(object sender, MouseButtonEventArgs e)
        {
            Rectangle clickedRectangle = sender as Rectangle;

            switch (clickedRectangle.Name)
            {
                case "top":
                    this.Cursor = Cursors.SizeNS;
                    ResizeWindow(ResizeDirection.Top);
                    break;
                case "bottom":
                    this.Cursor = Cursors.SizeNS;
                    ResizeWindow(ResizeDirection.Bottom);
                    break;
                case "left":
                    this.Cursor = Cursors.SizeWE;
                    ResizeWindow(ResizeDirection.Left);
                    break;
                case "right":
                    this.Cursor = Cursors.SizeWE;
                    ResizeWindow(ResizeDirection.Right);
                    break;
                case "topLeft":
                    this.Cursor = Cursors.SizeNWSE;
                    ResizeWindow(ResizeDirection.TopLeft);
                    break;
                case "topRight":
                    this.Cursor = Cursors.SizeNESW;
                    ResizeWindow(ResizeDirection.TopRight);
                    break;
                case "bottomLeft":
                    this.Cursor = Cursors.SizeNESW;
                    ResizeWindow(ResizeDirection.BottomLeft);
                    break;
                case "bottomRight":
                    this.Cursor = Cursors.SizeNWSE;
                    ResizeWindow(ResizeDirection.BottomRight);
                    break;
                default:
                    break;
            }
        }

        private void DisplayResizeCursor(object sender, MouseEventArgs e)
        {
            Rectangle clickedRectangle = sender as Rectangle;

            switch (clickedRectangle.Name)
            {
                case "top":
                    this.Cursor = Cursors.SizeNS;
                    break;
                case "bottom":
                    this.Cursor = Cursors.SizeNS;
                    break;
                case "left":
                    this.Cursor = Cursors.SizeWE;
                    break;
                case "right":
                    this.Cursor = Cursors.SizeWE;
                    break;
                case "topLeft":
                    this.Cursor = Cursors.SizeNWSE;
                    break;
                case "topRight":
                    this.Cursor = Cursors.SizeNESW;
                    break;
                case "bottomLeft":
                    this.Cursor = Cursors.SizeNESW;
                    break;
                case "bottomRight":
                    this.Cursor = Cursors.SizeNWSE;
                    break;
                default:
                    break;
            }
        }

        public enum ResizeDirection
        {
            Left = 1,
            Right = 2,
            Top = 3,
            TopLeft = 4,
            TopRight = 5,
            Bottom = 6,
            BottomLeft = 7,
            BottomRight = 8,
        }

        #endregion

        #region Maximize Window Related

        // code from http://stackoverflow.com/questions/2584321/customly-chromed-windows-in-wpf

        [DllImport("user32")]
        internal static extern bool GetMonitorInfo(IntPtr hMonitor, MONITORINFO lpmi);

        [DllImport("User32")]
        internal static extern IntPtr MonitorFromWindow(IntPtr handle, int flags);

        private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            switch (msg)
            {
                case 0x0024:
                    WmGetMinMaxInfo(hwnd, lParam);
                    handled = true;
                    break;
            }

            return (IntPtr)0;
        }

        private static void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam)
        {
            MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor
            int MONITOR_DEFAULTTONEAREST = 0x00000002;
            IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

            if (monitor != IntPtr.Zero)
            {
                MONITORINFO monitorInfo = new MONITORINFO();
                GetMonitorInfo(monitor, monitorInfo);
                RECT rcWorkArea = monitorInfo.rcWork;
                RECT rcMonitorArea = monitorInfo.rcMonitor;
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            /// <summary>
            /// x coordinate of point.
            /// </summary>
            public int x;
            /// <summary>
            /// y coordinate of point.
            /// </summary>
            public int y;

            /// <summary>
            /// Construct a point of coordinates (x,y).
            /// </summary>
            public POINT(int x, int y)
            {
                this.x = x;
                this.y = y;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MINMAXINFO
        {
            public POINT ptReserved;
            public POINT ptMaxSize;
            public POINT ptMaxPosition;
            public POINT ptMinTrackSize;
            public POINT ptMaxTrackSize;
        };

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public class MONITORINFO
        {
            /// <summary>
            /// </summary>            
            public int cbSize = Marshal.SizeOf(typeof(MONITORINFO));

            /// <summary>
            /// </summary>            
            public RECT rcMonitor = new RECT();

            /// <summary>
            /// </summary>            
            public RECT rcWork = new RECT();

            /// <summary>
            /// </summary>            
            public int dwFlags = 0;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct RECT
        {
            /// <summary> Win32 </summary>
            public int left;
            /// <summary> Win32 </summary>
            public int top;
            /// <summary> Win32 </summary>
            public int right;
            /// <summary> Win32 </summary>
            public int bottom;

            /// <summary> Win32 </summary>
            public static readonly RECT Empty = new RECT();

            /// <summary> Win32 </summary>
            public int Width
            {
                get { return Math.Abs(right - left); }  // Abs needed for BIDI OS
            }
            /// <summary> Win32 </summary>
            public int Height
            {
                get { return bottom - top; }
            }

            /// <summary> Win32 </summary>
            public RECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }


            /// <summary> Win32 </summary>
            public RECT(RECT rcSrc)
            {
                this.left = rcSrc.left;
                this.top = rcSrc.top;
                this.right = rcSrc.right;
                this.bottom = rcSrc.bottom;
            }

            /// <summary> Win32 </summary>
            public bool IsEmpty
            {
                get
                {
                    // BUGBUG : On Bidi OS (hebrew arabic) left > right
                    return left >= right || top >= bottom;
                }
            }
            /// <summary> Return a user friendly representation of this struct </summary>
            public override string ToString()
            {
                if (this == RECT.Empty) { return "RECT {Empty}"; }
                return "RECT { left : " + left + " / top : " + top + " / right : " + right + " / bottom : " + bottom + " }";
            }

            /// <summary> Determine if 2 RECT are equal (deep compare) </summary>
            public override bool Equals(object obj)
            {
                if (!(obj is Rect)) { return false; }
                return (this == (RECT)obj);
            }

            /// <summary>Return the HashCode for this struct (not garanteed to be unique)</summary>
            public override int GetHashCode()
            {
                return left.GetHashCode() + top.GetHashCode() + right.GetHashCode() + bottom.GetHashCode();
            }


            /// <summary> Determine if 2 RECT are equal (deep compare)</summary>
            public static bool operator ==(RECT rect1, RECT rect2)
            {
                return (rect1.left == rect2.left && rect1.top == rect2.top && rect1.right == rect2.right && rect1.bottom == rect2.bottom);
            }

            /// <summary> Determine if 2 RECT are different(deep compare)</summary>
            public static bool operator !=(RECT rect1, RECT rect2)
            {
                return !(rect1 == rect2);
            }

        }

        #endregion



        public MainWindow()
        {
            InitializeComponent();
            tvViewerPage = new TVViewer.Pages.TVViewer(this.MediaElement);
           //contentFrame.Navigate(tvViewerPage);         
            MediaElement.Play(@"d:\t_guildw2_gc09_debut_tr_hd.wmv");
            
       
        }

        private void ChangeVisibility(Visibility visible)
        {
            switch (visible)
            {
                case System.Windows.Visibility.Hidden:
                    brdSettings.Visibility = System.Windows.Visibility.Hidden;
                    lblGroups.Visibility = System.Windows.Visibility.Hidden;
                    lblServerName.Visibility = System.Windows.Visibility.Hidden;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Hidden;
                    chbIsIntranet.Visibility = System.Windows.Visibility.Hidden;
                    btnCheckServer.Visibility = System.Windows.Visibility.Hidden;
                    btnSave.Visibility = System.Windows.Visibility.Hidden;
                    tbServerName.Visibility = System.Windows.Visibility.Hidden;
                    complete_overlay.Visibility = System.Windows.Visibility.Hidden;
                    details_overlay.Visibility = System.Windows.Visibility.Hidden;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Hidden;
                    topRectangle.Visibility = System.Windows.Visibility.Hidden;
                    break;
                case System.Windows.Visibility.Visible:
                    brdSettings.Visibility = System.Windows.Visibility.Visible;
                    lblGroups.Visibility = System.Windows.Visibility.Visible;
                    lblServerName.Visibility = System.Windows.Visibility.Visible;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Visible;
                    chbIsIntranet.Visibility = System.Windows.Visibility.Visible;
                    btnCheckServer.Visibility = System.Windows.Visibility.Visible;
                    btnSave.Visibility = System.Windows.Visibility.Visible;
                    tbServerName.Visibility = System.Windows.Visibility.Visible;
                    complete_overlay.Visibility = System.Windows.Visibility.Visible;
                    details_overlay.Visibility = System.Windows.Visibility.Visible;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Visible;
                    topRectangle.Visibility = System.Windows.Visibility.Visible;
                    break;

            }

        }


        public void ConnectToService(string serverName)
        {
            try
            {
                if (Properties.Settings.Default.IsIntranet)
                {
                    try
                    {
                        tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, serverName)));
                    }
                    catch (CommunicationException ex)
                    {
                        tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, serverName)));

                    }
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                string sMessageBoxText = "Verbindung konnte nicht hergestellt werden. Erneut versuchen?";
                string sCaption = "TVViewer";

                MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

                MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);


                // Process message box results

                switch (rsltMessageBox)
                {

                    case MessageBoxResult.Yes:
                        ConnectToService(serverName);

                        break;
                    case MessageBoxResult.No:

                        break;
                }
            }

        }
        private void GetTVServerData(bool IsIntranet, string serverName)
        {
            try
            {
                if (IsIntranet) // Intranet
                {
                    ConnectToService(serverName);
                }
                else // Internet
                {

                }

                List<WebChannelGroup> groups = tvWebClient.GetGroups();
                cbChooseGroup.ItemsSource = groups;

                if (Properties.Settings.Default.DefaultGroup != 1)
                {
                    for (int i = 0; i < groups.Count; i++)
                    {

                        if (Properties.Settings.Default.DefaultGroup == groups[i].IdGroup)
                        {
                            cbChooseGroup.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    cbChooseGroup.SelectedIndex = 0;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        #region Events
        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (contentFrame.CanGoBack)
            {
                contentFrame.GoBack();
            }
        }
        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            ChangeVisibility(System.Windows.Visibility.Visible);
            tbServerName.Text = Properties.Settings.Default.ServerName;
        }

        private void complete_overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChangeVisibility(System.Windows.Visibility.Hidden);
        }
        private void btnCheckServer_Click(object sender, RoutedEventArgs e)
        {

            if (tbServerName.Text != "")
            {

                try
                {
                    GetTVServerData((bool)chbIsIntranet.IsChecked, tbServerName.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.IsIntranet = (bool)chbIsIntranet.IsChecked;
            if (tbServerName.Text != "")
            {
                Properties.Settings.Default.ServerName = tbServerName.Text;
                if (cbChooseGroup.SelectedItem is WebChannelGroup)
                {
                    Properties.Settings.Default.DefaultGroup = ((WebChannelGroup)cbChooseGroup.SelectedItem).IdGroup;
                }
                else
                {

                    Properties.Settings.Default.DefaultGroup = 1;
                }
                Properties.Settings.Default.Save();
                ChangeVisibility(System.Windows.Visibility.Hidden);
                tvViewerPage.FillPage();
            }

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            tvViewerPage.StopTimeshifting();
        }

        private void TVViewerMain_Loaded(object sender, RoutedEventArgs e)
        {
            if (Properties.Settings.Default.ServerName == "")
            {
                ChangeVisibility(System.Windows.Visibility.Visible);
            }
            else
            {
                GetTVServerData(Properties.Settings.Default.IsIntranet, Properties.Settings.Default.ServerName);
            }


        }

        private void btnSchedulesPage_Click(object sender, RoutedEventArgs e)
        {
            contentFrame.Navigate(tvSchedulesPage);
        }

        private void btnTVViewerPage_Click(object sender, RoutedEventArgs e)
        {
            contentFrame.Navigate(tvViewerPage);
        }
        #endregion

        private void btnCloseSettings_Click(object sender, RoutedEventArgs e)
        {
            complete_overlay_MouseLeftButtonDown(this, null);
        }

        private void btnFullscreen_Click(object sender, RoutedEventArgs e)
        {
            TimeSpan temp = MediaElement.Position;

            ContentFrameGrid.Children.Remove(MediaElement);
            Windows.Fullscreen fs = new Windows.Fullscreen(MediaElement);
            fs.Position = temp;
            fs.ShowDialog();
            if (fs.DialogResult.GetValueOrDefault(false))
            { 
               this.MediaElement = fs.MediaPlayerElement;
               ContentFrameGrid.Children.Add(MediaElement);
               MediaElement.Position = fs.Position;
            }
         
           
        }
   

    }
}
